package com.muzhongyun.codegenerator;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * Mybatis的代码生成器
 *
 * @author HeYongSheng
 */
public class MyBatisGeneratorUtil {

	public static void main(String[] args) throws Exception {

		// 验证path
		checkPath();
		List<String> warnings = new ArrayList<>();
		boolean overwrite = true;
		ConfigurationParser cp = new ConfigurationParser(warnings);
		Configuration config = cp.parseConfiguration(MyBatisGeneratorUtil.class.getResourceAsStream("/generator/generatorConfig.xml"));
		DefaultShellCallback callback = new DefaultShellCallback(overwrite);
		MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
		myBatisGenerator.generate(null);
		System.out.println("生成成功！");
	}

	/**
	 * 检查路径
	 */
	public static void checkPath(){
		Properties prop = new Properties();
		try {
			prop.load(MyBatisGeneratorUtil.class.getResourceAsStream("/generator/generatorConfig.properties"));
			// 文档根目录
			String basePath = prop.getProperty("basePath");
			// mapper xml 目录
			String mapperXmlPath = prop.getProperty("mapperXml.path");
			exitsDir(basePath,mapperXmlPath);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 验证目录是否存在
	 * @param dirs 多个目录地址
	 */
	public static void exitsDir(String ... dirs){
		for (String dir : dirs){
			File file = new File(dir);
			if (!file.exists()) {
				System.err.println("目录：" + dir + "不存在，开始创建……");
				file.mkdirs();
			}
		}

	}
}
